package service

import (
	"database/sql"
	"hy_808/di"
	"hy_808/global"
	"hy_808/logdot"
	"hy_808/protocol/jtt808"
	"hy_808/protocol/jtt808/packet/d2p"
	"hy_808/protocol/jtt808/packet/p2d"
	"hy_808/tcpx"
)

var Client808 = Client808Service{
	Logger: di.Logdot(),
}

type Client808Service struct {
	Logger *logdot.Logdot
}

func (this Client808Service) OnReceive(c *tcpx.Conn, p jtt808.Jtt808) bool {
	switch p.Head.GetId() {
	case 0x8100: //平台对终端注册应答
		pa := p2d.ParsePlatformRegAnswer(p)
		this.Handle8100(c, pa)
		break
	case jtt808.PlatformAnswerId: //平台给终端的应答
		pa := p2d.ParsePlatformAnswer(p)
		this.Handle8001(c, pa)
		break
	}
	return true
}

// 处理注册平台得应答
func (this Client808Service) Handle8100(conn *tcpx.Conn, pa p2d.PlatformRegAnswer) {
	seq := pa.AnswerRegSN
	switch pa.Result {
	case 0:
		this.Logger.Info("注册成功,收到注册应答", seq, pa.TokenCode)
		phone := pa.Head.GetPhoneStr()
		dc := DeviceEntity.GetDeviceByPhone(phone)
		dc.TokenCode = pa.TokenCode
		data, err := GetRowByPhone(phone)
		if err == sql.ErrNoRows {
			SaveDeviceToDB(phone, dc.BusNo, dc.TokenCode)
		}
		this.Authenticate(data.TokenCode, conn)
		break
	case 1: //车辆已被注册
		this.Logger.Info("车辆已被注册", seq)
		break
	case 2:
		this.Logger.Info("数据库中无该车辆", seq)
		break
	case 3:
		this.Logger.Info("终端已被注册", seq)
		break
	case 4:
		this.Logger.Info("数据库中无该终端", seq)
		break
	}

}

// 处理平台通用应答
func (this Client808Service) Handle8001(conn *tcpx.Conn, pa p2d.PlatformAnswer) {
	seq := pa.AnswerRegSN
	//s2 := strconv.FormatInt(int64(pa.AnswerForId), 16) //10 转2进制
	this.Logger.Info("收到平台通用应答,流水号", seq, "应答ID,", pa.AnswerForId, ",应答结果", pa.Result)
	switch pa.Result {
	case 0:
		dc := this.GetDeviceByConn(conn)
		dc.SignIn = true
		break
	case 1: //车辆已被注册
		this.Logger.Info("失败", pa.AnswerForId, seq)
		break
	case 2:
		this.Logger.Info("消息有误", pa.AnswerForId, seq)
		break
	case 3:
		this.Logger.Info("不支持", pa.AnswerForId, seq)
		break
	}
}

func (this Client808Service) Authenticate(tokenCode string, conn *tcpx.Conn) {
	au := d2p.GenAuthenticate(tokenCode)
	conn.Send(tcpx.MakePackage(au.Data))
	//DeviceDBDataMap.Load()
}

func (this Client808Service) GetDeviceByConn(conn *tcpx.Conn) *global.DeviceClient {
	dc := DeviceEntity.GetDeviceByConn(conn.LocalAddr().String())
	return dc
}
